package com.sdy.usercenter.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.MapUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.mq.service.MqProducerService;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.utils.HttpUtil;
import com.sdy.usercenter.biz.constants.MqConstants;
import com.sdy.usercenter.biz.model.SysApplication;
import com.sdy.usercenter.biz.model.SysLog;
import com.sdy.usercenter.biz.model.SysResource;
import com.sdy.usercenter.biz.model.SysUser;
import com.sdy.usercenter.biz.model.SysUserApp;
import com.sdy.usercenter.biz.service.SysApplicationService;
import com.sdy.usercenter.biz.service.SysResourceService;
import com.sdy.usercenter.biz.service.SysUserAppService;
import com.sdy.usercenter.biz.service.SysUserService;
import com.sdy.usercenter.web.constants.WebConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统资源表 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2019-06-14
 */
@Slf4j
@RestController
@RequestMapping("/sysResource")
public class SysResourceController extends BaseController {
    @Autowired
    private SysResourceService sysResourceService;
    @Autowired
    private MqProducerService mqProducerService;
    @Autowired
    private SysUserAppService sysUserAppService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private SysApplicationService sysApplicationService;
    
    @GetMapping("/get")
    public Response get(Integer id) {
        return Response.success(sysResourceService.getById(id));
    }
    
    @GetMapping("/appTreeData")
    public Response appTreeData(String appCode) throws BizException {
        return Response.success(sysResourceService.appTreeData(appCode, false));
    }

    /**
     * 分页数据
     */
    @GetMapping("/srcPageData")
    public Response srcPageData(HttpServletRequest request, Page<SysUser> page, Integer appId) {
        Map<String, Object> queryMap = new HashMap<>();
        String name = request.getParameter("name");
        if (StringUtil.isNotBlank(name)) {
            queryMap.put("name", name);
        }
        IPage<SysUser> result = sysUserService.pageUserWithApp(page, queryMap, appId, false);
        return Response.success(result);
    }

    /**
     * 分页数据
     */
    @GetMapping("/destPageData")
    public Response destPageData(HttpServletRequest request, Page<SysUser> page, Integer appId) {
        Map<String, Object> queryMap = new HashMap<>();
        String name = request.getParameter("name");
        if (StringUtil.isNotBlank(name)) {
            queryMap.put("name", name);
        }
        IPage<SysUser> result = sysUserService.pageUserWithApp(page, queryMap, appId, true);
        return Response.success(result);
    }

    /**
     * 添加用户
     */
    @GetMapping("/addUsers")
    public Response addUser(HttpServletRequest request, Integer[] userIds, Integer appId) throws Exception {
        if (userIds != null) {
            sysUserAppService.addUsers(Arrays.asList(userIds), appId);
            // 日志消息
            UserInfo opUserInfo = ssoService.getUserInfo(request);
            mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                    SysLog.LogType.APP_AUTH_ADD.getTypeS().concat(MqConstants.SEP_TOKEN)
                            .concat(opUserInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                            .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                            .concat(HttpUtil.getIpAddr(request)).concat(MqConstants.SEP_TOKEN)
                            .concat(opUserInfo.getUserName() + " 添加系统权限APPID：" + appId + "，用户ID：" + Arrays.toString(userIds))
            );
        }
        return Response.success();
    }

    /**
     * 移除用户
     */
    @GetMapping("/removeUsers")
    public Response removeUsers(HttpServletRequest request, Integer[] userIds, Integer appId) throws Exception {
        if (userIds != null) {
            sysUserAppService.removeUsers(Arrays.asList(userIds), appId);
            // 日志消息
            UserInfo opUserInfo = ssoService.getUserInfo(request);
            mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                    SysLog.LogType.APP_AUTH_DEL.getTypeS().concat(MqConstants.SEP_TOKEN)
                            .concat(opUserInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                            .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                            .concat(HttpUtil.getIpAddr(request)).concat(MqConstants.SEP_TOKEN)
                            .concat(opUserInfo.getUserName() + " 移除系统权限APPID：" + appId + "，用户ID：" + Arrays.toString(userIds))
            );
        }
        return Response.success();
    }

    /**
     * 分页数据
     * @param request
     * @param page [current, size]
     * @return
     */
    @GetMapping("/pageData")
    public Response pageData(HttpServletRequest request, Page<SysResource> page) {
        QueryWrapper<SysResource> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");

        IPage<SysResource> result = sysResourceService.page(page, wrapper);
        return Response.success(result);
    }

    /**
     * 树数据
     */
    @GetMapping("/listData")
    public Response listData() {
        LambdaQueryWrapper<SysResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SysResource::getSort, SysResource::getId);
        List<SysResource> result = sysResourceService.list(wrapper);
        return Response.success(result);
    }

    /**
     * 保存数据
     * @param
     * @return
     */
    @PostMapping("/save")
    public Response save(HttpServletRequest request, @RequestBody SysResource sysResource) throws Exception {
        sysResourceService.createResource(sysResource);
        // 日志消息
        UserInfo opUserInfo = ssoService.getUserInfo(request);
        mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                SysLog.LogType.ADD_RES.getTypeS().concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                        .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                        .concat(HttpUtil.getIpAddr(request)).concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserName() + " 新建资源：" + sysResource.getName() + " [" + sysResource.getId() + "]")
        );
        return Response.success(sysResource);
    }

    /**
     * 更新数据
     * @param
     * @return
     */
    @PostMapping("/update")
    public Response update(HttpServletRequest request, @RequestBody SysResource sysResource) throws Exception {
        Assert.isNull(sysResource.getId(), "资源ID不能为空！");
        sysResourceService.updateResource(sysResource);
        // 日志消息
        UserInfo opUserInfo = ssoService.getUserInfo(request);
        mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                SysLog.LogType.EDIT_RES.getTypeS().concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                        .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                        .concat(HttpUtil.getIpAddr(request)).concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserName() + " 编辑资源：" + sysResource.getName() + " [" + sysResource.getId() + "]")
        );
        return Response.success();
    }

    /**
     * 删除数据
     * @param id 主键
     * @return
     */
    @GetMapping("/delete")
    public Response delete(Integer id) {
        sysResourceService.deleteResource(Collections.singletonList(id));
        return Response.success();
    }

    /**
     * 禁用
     */
    @GetMapping("/disableResource")
    public Response disableResource(Integer id) {
        boolean r = sysResourceService.lambdaUpdate().eq(SysResource::getId, id).set(SysResource::getState, 2).update();
        if (!r) {
            return Response.error("禁用失败！");
        }
        return Response.success();
    }

    /**
     * 启用
     */
    @GetMapping("/enableResource")
    public Response enableResource(Integer id) {
        boolean r = sysResourceService.lambdaUpdate().eq(SysResource::getId, id).set(SysResource::getState, 1).update();
        if (!r) {
            return Response.error("启用失败！");
        }
        return Response.success();
    }
}
